import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'
import { useDispatch } from 'react-redux'
import { getCode, login } from '@/store/actions/login'

import styles from './index.module.scss'
import Icon from '@/components/Icon'

import { AxiosError } from 'axios'
import { useRef } from 'react'
import { InputRef } from 'antd-mobile/es/components/input/input'
import { useCountDown } from '@/hooks/useCountDown'
import { useHistory, useLocation } from 'react-router-dom'
type LoginForm = {
mobile: string
code: string
}
const Login = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const mobileInp = useRef<InputRef>(null)
  // 注意： state 可能是不存在的，所以，类型中要明确包含不存在的情况，即 undefined
  const location = useLocation<{ from: string } | undefined>()
  // 登录
  const onFinish = async (values: LoginForm) => {
    try {
      await dispatch(login(values))
      // 登录成功提示
      Toast.show({
        content: '登录成功',
        duration: 600,
        afterClose: () => {
          if (location.state) {
            return history.replace(location.state.from)
          }

          history.replace('/home/index')
        }
      })
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      console.log(error.response?.data.message)

      Toast.show({
        content: error.response?.data.message || '登录失败请检查网络',
        duration: 1000
      })
    }
  }
  const { flag, setCount, start, timeText } = useCountDown()
  // 获取验证码
  const onSend = async () => {
    form.validateFields(['mobile'])
    const mobile = form.getFieldValue('mobile')
    const hasError = form.getFieldError('mobile').length > 0
    if (!mobile || hasError) return mobileInp.current?.focus()

    try {
      start()
      setCount(60)
      await dispatch(getCode(mobile))
      Toast.show({ content: '短信已发送' })
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      Toast.show({ content: error.response?.data.message })
    }
  }
  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form form={form} onFinish={onFinish}>
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误'
              }
            ]}
          >
            <Input ref={mobileInp} placeholder="请输入手机号" />
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={<span className="code-extra" onClick={flag ? onSend : () => {}}>{timeText}</span>}
          >
            <Form.Item
              className="login-item"
              name="code"
              rules={[{ required: true, message: '请输入验证码' }]}
            >
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className="elesLogin">
        <span>使用其他方式登录 |</span>
        <Icon type="icon-weixin" className="eles" />
        <Icon type="icon-qq" className="eles" />
      </div>
    </div>
  )
}
export default Login
